package com.agent.commons.intercept;

import com.agent.commons.other.ThreadLocal;
import com.agent.commons.utils.Sm4Util;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 模块拦截器
 */
@Slf4j
@Component
public class ModuleInterceptor implements HandlerInterceptor {

    public ModuleInterceptor() {
        log.info("✅ 模块拦截器初始化!");
    }

    /**
     * 请求前操作拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true; // 直接放行
        }
        //获取请求头中传递过来的基本信息
        String userId = request.getHeader("userId");
        //中文字符解码
        String userName = URLDecoder.decode(request.getHeader("userName"), StandardCharsets.UTF_8);
        //获取请求头中传递过来的角色信息
        String role = request.getHeader("userRole");
        //设置线程变量
        ThreadLocal.setUserId(userId);
        ThreadLocal.setUserName(userName);
        ThreadLocal.setRole(role);
        log.debug("userId:{},userName:{}",userId,userName);
        //获取头参数ds
        String key= request.getHeader("key");
        log.debug("key:{}",key);
        //根据key进行Sm4解密，判断信息是否被篡改
        if(key==null||userId==null||userName==null){
            log.error("验证参数错误！key:{},userId:{},userName:{}",key,userId,userName);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }else {
            String decrypt = Sm4Util.decrypt(key);
            log.debug("decrypt:{}", decrypt);
            //被篡改，进行拦截
            if (!decrypt.equals(userId + "-" + userName)) {
                log.error("网关传递信息被篡改！");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
        }
        //放行
        return true;
    }

    /**
     * 请求执行后操作
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("请求执行完毕！");
        //清除线程变量
        ThreadLocal.remove();
    }

}
